﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using GorgonLibrary.Graphics;
using System.Drawing;
using EngineOfEvermore.Common;
using EngineOfEvermore.Scene.Physics;

namespace EngineOfEvermore.Scene
{
    public sealed class SceneGraph
    {
        #region class ComponentWaitQueue
        class ComponentWaitQueue
        {
            enum QueueAction
            {
                ADD,
                REMOVE
            }

            struct Entry
            {
                public Entry( SceneObject targetSceneObject, SceneObjectComponent component, 
                    QueueAction action )
                {
                    TargetSceneObject = targetSceneObject;
                    Component = component;
                    Action = action;
                }

                public readonly SceneObject TargetSceneObject;
                public readonly SceneObjectComponent Component;
                public readonly QueueAction Action;
            }

            Queue<Entry> _waitQueue = new Queue<Entry>();

            public bool IsEmpty
            {
                get { return _waitQueue.Count == 0; }
            }

            public void EnqueueForAddition( SceneObject targetSceneObject,
                SceneObjectComponent component )
            {
                Debug.Assert( !_waitQueue.Any( x => x.Component == component ) );
                _waitQueue.Enqueue( new Entry( targetSceneObject, component, QueueAction.ADD ) );
            }

            public void EnqueueForRemoval( SceneObject targetSceneObject, 
                SceneObjectComponent component )
            {
                Debug.Assert( !_waitQueue.Any( x => x.Component == component ) );
                _waitQueue.Enqueue( 
                    new Entry( targetSceneObject, component, QueueAction.REMOVE ) 
                    );
            }

            public bool ContainsForAddition( SceneObject targetSceneObject, 
                SceneObjectComponent component )
            { 
                Entry entry = new Entry( targetSceneObject, component, QueueAction.ADD );
                return _waitQueue.Contains( entry );
            }

            public bool ContainsForRemoval( SceneObject targetSceneObject, 
                SceneObjectComponent component )
            {
                Entry entry = new Entry( targetSceneObject, component, QueueAction.REMOVE );
                return _waitQueue.Contains( entry );
            }

            public void PerformAdditionsAndRemovals()
            {
                while ( _waitQueue.Count != 0 )
                {
                    Entry entry = _waitQueue.Dequeue();

                    if ( entry.Action == QueueAction.ADD )
                    {
                        entry.TargetSceneObject.AddComponent( entry.Component );
                    }
                    else
                    {
                        entry.TargetSceneObject.RemoveComponent( entry.Component );
                    }
                }
            }
        }
        #endregion

        #region class PhysicsUpdateTask
        class PhysicsUpdateTask : Task
        {
            SceneGraph _owner;

            public PhysicsUpdateTask( SceneGraph owner ):
                base( 1000 )
            {
                _owner = owner;
            }

            public override void Execute( LogicUpdateEventArgs e )
            {
                _owner._physics.Update( e );
            }
        }
        #endregion

        #region Variables
        LinkedList<SceneSubSystem> _subSystems;
        IServiceProvider _services;
        IList<SceneObject> _sceneObjects;

        List<SceneObject> _sceneObjectsToBeRemoved;
        List<SceneObject> _sceneObjectsToBeAdded;

        ITimeContext _timeContext;

        ComponentWaitQueue _componentWaitQueue;
        InternalPhysicsManager _physics;
        PhysicsUpdateTask _physicsUpdateTask;
        #endregion

        #region Properties
        public ITimeContext TimeContext
        {
            get { return _timeContext; }
        }
        #endregion

        #region Constructor
        public SceneGraph()
        {
            _subSystems = new LinkedList<SceneSubSystem>();
            _sceneObjects = new List<SceneObject>();
            
            _sceneObjectsToBeAdded = new List<SceneObject>();
            _sceneObjectsToBeRemoved = new List<SceneObject>();

            _componentWaitQueue = new ComponentWaitQueue();
            _physicsUpdateTask = new PhysicsUpdateTask( this );
        }
        #endregion

        #region Methods
        public void OnInit( IServiceProvider services )
        {
            _services = services;

            _timeContext = (ITimeContext) _services.GetService( typeof( ITimeContext ) );
            _timeContext.PostUpdate += _postUpdate;

            _physics = new InternalPhysicsManager();
            _timeContext.AddRepeatingTask( _physicsUpdateTask );
            _physics.CollisionGroupSetup = "/Configuration/DefaultCollisionConfig.collisionsetup";

            // initialize SubSystems, maybe with plugins later
            _addSubSystem( new Visual.VisualSubSystem() );
            _addSubSystem( new Physics.CollisionSubSystem( _physics ) );
            _addSubSystem( new Input.InputSubSystem() );
        }

        public void OnDeInit( IServiceProvider services )
        {
            List<SceneSubSystem> subSystemList = 
                new List<SceneSubSystem>( _subSystems );

            foreach ( SceneSubSystem subSystem in subSystemList )
            {
                _removeSubSystem( subSystem );
            }

            _timeContext.RemoveRepeatingTask( _physicsUpdateTask );
            _physics.Dispose();
            _physics = null;

            _timeContext = null;
            _services = null;
        }

        public IEnumerable<SceneObject> SceneObjects
        {
            get { return _sceneObjects; }
        }

        public void AddSceneObject( SceneObject sceneObject )
        {
            Debug.Assert( sceneObject.SceneGraph == null );
            Debug.Assert( !_sceneObjects.Contains( sceneObject ) );
            Debug.Assert( !_sceneObjectsToBeAdded.Contains( sceneObject ) );

            if ( _timeContext.IsUpdating )
            {
                _sceneObjectsToBeAdded.Add( sceneObject );
            }
            else
            {
                _sceneObjects.Add( sceneObject );
                _physics.RegisterSceneObject( sceneObject );
                sceneObject.OnAddToScene( this );
            }
        }

        public void RemoveSceneObject( SceneObject sceneObject )
        {
            Debug.Assert( sceneObject.SceneGraph == this );
            Debug.Assert( _sceneObjects.Contains( sceneObject ) );
            Debug.Assert( !_sceneObjectsToBeRemoved.Contains( sceneObject ) );

            if ( _timeContext.IsUpdating )
            {
                _sceneObjectsToBeRemoved.Add( sceneObject );
            }
            else
            {
                sceneObject.OnRemoveFromScene( this );
                _physics.UnregisterSceneObject( sceneObject );
                _sceneObjects.Remove( sceneObject );
            }
        }

        public void Clear()
        {
            if ( _timeContext.IsUpdating )
            {
                _sceneObjectsToBeRemoved.AddRange(
                    _sceneObjects.Except( _sceneObjectsToBeRemoved ) );
            }
            else
            {
                while ( _sceneObjects.Count > 0 )
                {
                    int index = _sceneObjects.Count - 1;
                    _sceneObjects[index].OnRemoveFromScene( this );
                    _physics.UnregisterSceneObject( _sceneObjects[index] );
                    _sceneObjects.RemoveAt( index );
                }
            }
        }

        public T GetSubSystem<T>() where T : SceneSubSystem
        {

            foreach ( SceneSubSystem subSystem in _subSystems )
            {
                if ( subSystem is T )
                {
                    return (T) subSystem;
                }
            }

            return null;
        }

        void _addSubSystem( SceneSubSystem subSystem )
        {
            _subSystems.AddLast( subSystem );

            subSystem.OnInit( _services );

            foreach ( SceneSubSystem sibling in _subSystems )
            {
                if ( sibling != subSystem )
                {
                    subSystem.OnSiblingAdded( sibling );
                    sibling.OnSiblingAdded( subSystem );
                }
            }
        }

        void _removeSubSystem( SceneSubSystem subSystem )
        {
            Debug.Assert( _subSystems.Contains( subSystem ) );
            
            foreach ( SceneSubSystem sibling in _subSystems )
            {
                if ( sibling != subSystem )
                {
                    sibling.OnSiblingRemoved( subSystem );
                    subSystem.OnSiblingRemoved( sibling );
                }
            }

            subSystem.OnDeInit( _services );

            _subSystems.Remove( subSystem );
        }

        void _postUpdate()
        {
            if ( !_componentWaitQueue.IsEmpty )
            {
                _componentWaitQueue.PerformAdditionsAndRemovals();
            }

            if ( _sceneObjectsToBeRemoved.Count > 0 )
            {
                List<SceneObject> buffer = new List<SceneObject>( _sceneObjectsToBeRemoved );
                _sceneObjectsToBeRemoved.Clear();

                foreach ( SceneObject entity in buffer )
                {
                    RemoveSceneObject( entity );
                }
            }

            if ( _sceneObjectsToBeAdded.Count > 0 )
            {
                List<SceneObject> buffer = new List<SceneObject>( _sceneObjectsToBeAdded );
                _sceneObjectsToBeAdded.Clear();

                foreach ( SceneObject entity in buffer )
                {
                    AddSceneObject( entity );
                }
            }
        }

        public void Draw( RectangleF visibleArea, FrameEventArgs e)
        {
            GetSubSystem<Visual.VisualSubSystem>().Draw( visibleArea, e );
        }

        internal void ScheduleComponentAddition( SceneObject sceneObject,
            SceneObjectComponent component )
        {
            _componentWaitQueue.EnqueueForAddition( sceneObject, component );
        }

        internal void ScheduleComponentRemoval( SceneObject sceneObject, 
            SceneObjectComponent component )
        {
            _componentWaitQueue.EnqueueForRemoval( sceneObject, component );
        }

        internal bool IsComponentScheduledForAdding( SceneObject sceneObject,
            SceneObjectComponent component )
        {
            return _componentWaitQueue.ContainsForAddition( sceneObject, component );
        }

        internal bool IsComponentScheduledForRemoval( SceneObject sceneObject,
            SceneObjectComponent component )
        {
            return _componentWaitQueue.ContainsForRemoval( sceneObject, component );
        }
        #endregion
    }
}
